package weaver.interfaces.cese.duss.ceseutil;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.general.BaseBean;
import org.apache.axis.encoding.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import weaver.common.DateUtil;
import weaver.conn.RecordSet;
import weaver.docs.webservices.DocAttachment;
import weaver.docs.webservices.DocInfo;
import weaver.docs.webservices.DocServiceImpl;
import weaver.general.Util;
import weaver.hrm.User;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Title: ecology-9-demo
 * @Company: 泛微软件
 * @author: weaver.Dusongsong
 * @version: 1.0
 * @CreateDate: 2021-01-26
 * @Description: ${description}
 * @ModifyLog:
 **/

public class ImageUtil {
    /**
     * 对图片裁剪，并把裁剪完新图片保存 。
     */
    //生成新的文档
    public static int generateNewImage(int userid,int x, int y, int width, int height, int fileId, String rawFileName,int count) throws IOException {
        InputStream is = null;
        ImageInputStream iis = null;
        int docid=-1;
        try {
            String filetype = "";
            String filename = "";
            if (rawFileName.lastIndexOf( "." ) > -1) {
                filetype = rawFileName.substring( rawFileName.lastIndexOf( "." ) + 1 );
                filename = rawFileName.substring( 0, rawFileName.lastIndexOf( "." ) );
            }
            // 读取图片文件
            Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName( filetype );
            ImageReader reader = it.next();
            // 获取图片流
            is = OcrUitl.getInputStreamById( fileId );
            iis = ImageIO.createImageInputStream( is );
            reader.setInput( iis, true );
            ImageReadParam param = reader.getDefaultReadParam();
            Rectangle rect = new Rectangle( x, y, width, height );
            // 提供一个 BufferedImage，将其用作解码像素数据的目标。
            param.setSourceRegion( rect );
            BufferedImage bi = reader.read( 0, param );


            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            ImageOutputStream imOut = ImageIO.createImageOutputStream(bs);
            boolean flag =  ImageIO.write(bi, filetype, imOut);
                byte[] bytes =  bs.toByteArray();
            InputStream inputStream = new ByteArrayInputStream(bytes);

            if (flag) {
                docid = createNewDoc( userid, inputStream, rawFileName,count);
            }
        } finally {
            if (is != null)
                is.close();
            if (iis != null)
                iis.close();
        }
        return docid;
    }
    //影像切割
    public static String imageCut(int userid, int fileId, String url, String appkey) {
        int docid = -1;
        String docids = "";
        BaseBean baseBean = new BaseBean();
        RecordSet rs = new RecordSet();
        BufferedImage sourceImg = null;
        try {
            String sql = "select imagefilename from imagefile where imagefileid in (select imagefileid from docimagefile where docid=" + fileId + ")";
            rs.executeQuery( sql );
            rs.next();
            String imagefilename = Util.null2String( rs.getString( "imagefilename" ) );
            InputStream inputStream = OcrUitl.getInputStreamById( fileId );
            sourceImg = ImageIO.read( inputStream );
            String result = OcrUitl.sendPostHttpOCR( url, fileId, appkey );
            JSONObject resultJson = JSONObject.parseObject( result );
            baseBean.writeLog( "影像切割接口返回：" + resultJson.toJSONString() );
            String code = resultJson.getString( "status" );
            if ("200".equals( code )) {
                JSONObject data = JSONObject.parseObject( resultJson.getString( "data" ) );
                String boxes = data.getString( "boxes" );
                JSONArray dataArray = JSONArray.parseArray( boxes );
                if (dataArray.size() > 1) {
                    for (int i = 0; i < dataArray.size(); i++) {
                        JSONObject results = (JSONObject) dataArray.get( i );
                        String box = results.getString( "box" );
                        String[] arr = StringUtils.strip( box, "[]" ).split( "," );
                        String y0 = BDC.floatMultiply( arr[0], sourceImg.getHeight() + "", 0 );
                        String x0 = BDC.floatMultiply( arr[1], sourceImg.getWidth() + "", 0 );
                        String y1 = BDC.floatMultiply( arr[2], sourceImg.getHeight() + "", 0 );
                        String x1 = BDC.floatMultiply( arr[3], sourceImg.getWidth() + "", 0 );
                        int x = Util.getIntValue( x0 );
                        int y = Util.getIntValue( y0 );
                        int width = Util.getIntValue( x1 ) - Util.getIntValue( x0 );
                        int heigth = Util.getIntValue( y1 ) - Util.getIntValue( y0 );
                        docid = generateNewImage(userid, x, y, width, heigth, fileId, imagefilename,i);
                        docids += docids == "" ? docid + "" : "," + docid;
                    }
                }
//                String tempFolderPath = "/home/weaver/ecology/classbean/weaver/interfaces/cese/duss/tempfolder/";
//                delAllFile(tempFolderPath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return docids;
    }
    //创建文档
    public static int createNewDoc(int userid, InputStream input,String rawFileName,int count){
        BaseBean log = new BaseBean();
        byte[] content = new byte[102400];
        // 上传附件，创建html文档
        content = null;
        try {
            int byteread;
            byte data[] = new byte[1024];
            //InputStream input = new FileInputStream(new File(path));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((byteread = input.read(data)) != -1) {
                out.write(data, 0, byteread);
                out.flush();
            }
            content = out.toByteArray();
            input.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        int docid = -1;
        DocServiceImpl docserviceimpl = new DocServiceImpl();
        DocAttachment[] docattachment = new DocAttachment[1];
        String docsubject = ""; //文档标题
        String keyword = ""; //文档内容
        String filetype = "";
        String filename = "";
        if (rawFileName.lastIndexOf( "." ) > -1) {
            filetype = rawFileName.substring( rawFileName.lastIndexOf( "." ) + 1 );
            filename = rawFileName.substring( 0, rawFileName.lastIndexOf( "." ) );
        }
        try {
        DocAttachment da = new DocAttachment();
        da.setFilename( filename+"_"+count+"."+filetype);//附件标题
        da.setFilecontent( Base64.encode(content)); //附件内容
        da.setFiletype( filetype ); //imagefiletype
        da.setImagefilename( filename+"_"+count+"."+filetype );// 附件标题
        da.setIszip( 1 );//是否压缩
        da.setIsAesEncrype( 0 );//是否加密
        da.setAesCode( "0" );
        da.setIsextfile( "1" ); //附件是否是office类型
        if (filetype.equalsIgnoreCase( "doc" )) {
            da.setDocfiletype( "3" );
        } else if (filetype.equalsIgnoreCase( "xls" )) {
            da.setDocfiletype( "4" );
        } else if (filetype.equalsIgnoreCase( "ppt" )) {
            da.setDocfiletype( "5" );
        } else if (filetype.equalsIgnoreCase( "wps" )) {
            da.setDocfiletype( "6" );
        } else if (filetype.equalsIgnoreCase( "docx" )) {
            da.setDocfiletype( "7" );
        } else if (filetype.equalsIgnoreCase( "xlsx" )) {
            da.setDocfiletype( "8" );
        } else if (filetype.equalsIgnoreCase( "pptx" )) {
            da.setDocfiletype( "9" );
        } else {
            da.setDocfiletype( "2" );
        }
        docattachment[0] = da;
        docsubject = filename;
        keyword = filename;
        DocInfo doc = new DocInfo();//创建文档
        doc.setMaincategory( 41 );//主目录id
        doc.setSubcategory( 6042 );//分目录id
        //doc.setSeccategory( 26541 );//子目录id
        doc.setDocSubject( docsubject );//标题
        doc.setDoccontent( "" );//文档内容
        doc.setKeyword( keyword );
        doc.setAttachments( docattachment );
        if (!"".equals( userid )) {
            User user = new User( userid );
            docid = docserviceimpl.createDocByUser( doc, user );
        }
    } catch (Exception e) {
        e.printStackTrace();
        log.writeLog( "e:" + e );
    }
        return docid;
    }
    // 删除文件
    public static void delAllFile(String path) {
        File file = new File( path );
        if (!file.exists()) {
            return;
        }
        if (!file.isDirectory()) {
            return;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith( File.separator )) {
                temp = new File( path + tempList[i] );
            } else {
                temp = new File( path + File.separator + tempList[i] );
            }
            if (temp.isFile()) {
                if (temp.exists()) {
                    temp.delete();
                }
            }
            if (temp.isDirectory()) {
                delAllFile( path + File.separator + tempList[i] );//删除文件夹里面的文件
            }
        }

    }
    //发送附件
    public static String sendAttachment(int fileId,String djbh,String hszz,String uploadUser){
        BaseBean baseBean = new BaseBean();
        String img_API_KEY = baseBean.getPropValue("langchao","IMG_API_KEY");
        String img_url =  baseBean.getPropValue("langchao","img_url");
        Map<String, Object> params = new HashMap<>();
        String clientcode = "WB";//调用系统代码
        String servicecode = "ImageCenter";//提供服务的系统编码
        String date = DateUtil.getFullDate().substring( 0, 10 ).replaceAll( "-", "" );
        String time = date + DateUtil.getFullDate().substring( 11, 19 ).replaceAll( ":", "" );//明文参数验证时，该节点必输，格式为：YYYYMMDDHHmmSS
        String ticket = time + servicecode + clientcode + img_API_KEY;//明文参数验证时，该节点必输，取值为：time值+ servicecode 值+ clientcode 值+约定KEY，生成的MD5值
        String md5Ticket = DigestUtils.md5Hex( ticket );
        String servername = "sendImage";//调用的服务标记
        String servertype = "";//调用的服务类型，0/实时接口，1/定时接口，影像系统可配置，默认取影像系统配置
        params.put( "clientcode", clientcode );
        params.put( "servicecode", servicecode );
        params.put( "time", time );
        params.put( "ticket", md5Ticket );
        params.put( "servername", servername );
        params.put( "servertype", servertype );

        int count = 1;
        String barcode = djbh;//单据编码或者合同号
        String filename = getImagefilename(fileId);//文件名（包括扩展名称）
        String content = Base64.encode(getContent(fileId));//图片或pdf序列化后的Base64值
        String compoanycode = hszz;//单位编号
        String useraccount = uploadUser;//上传用户
        String page = "1";//当前页数
        String totalpage = "1";//总记录
        params.put( "serviceid", count );
        params.put( "barcode", barcode );
        params.put( "filename", filename );
        params.put( "content", content );
        params.put( "compoanycode", compoanycode );
        params.put( "useraccount", useraccount );
        params.put( "ifhx", 0 );
        params.put( "page", page );
        params.put( "totalpage", totalpage );
        String param = XMLContent( params );
        String str = "param=" + param;
        baseBean.writeLog("str:"+str);
        Map<String,String> headers = new HashMap<>(  );
        headers.put("Content-Type","application/x-www-form-urlencoded");
        String returns = httpPostRaw(img_url,str,headers,"UTF-8");
        returns = returns.replaceAll("&lt;","<").replaceAll( "&gt;",">" );
        baseBean.writeLog("returns:"+returns);
        return returns;
    }
    //发生HTTP请求post
    public static String httpPostRaw(String url,String stringJson,Map<String,String> headers, String encode){
        BaseBean baseBean = new BaseBean();
        if(encode == null){
            encode = "utf-8";
        }
        String content = null;
        CloseableHttpResponse httpResponse = null;
        CloseableHttpClient closeableHttpClient = null;
        try {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public void checkClientTrusted(
                        java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                        String paramString) {
                }

                @Override
                public void checkServerTrusted(
                        java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                        String paramString) {
                }

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            sslcontext.init(null, new TrustManager[] { trustManager }, null);
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", new SSLConnectionSocketFactory(sslcontext)).build();
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);

            //HttpClients.createDefault()等价于 HttpClientBuilder.create().build();
            closeableHttpClient = HttpClients.createDefault();
            HttpPost httpost = new HttpPost(url);

            //设置header
            httpost.setHeader("Content-type", "application/json");
            if (headers != null && headers.size() > 0) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    httpost.setHeader(entry.getKey(),entry.getValue());
                }
            }
            //组织请求参数
            StringEntity stringEntity = new StringEntity(stringJson, encode);
            httpost.setEntity(stringEntity);

            //响应信息
            httpResponse = closeableHttpClient.execute(httpost);
            int code = httpResponse.getStatusLine().getStatusCode();
            baseBean.writeLog( "接口响应状态码："+code );
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {  //关闭连接、释放资源
            closeableHttpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
    //组装XML
    public static String XMLContent(Map<String, Object> map) {
        String result = "";
        JSONObject xml = new JSONObject();
        JSONObject params = new JSONObject();
        JSONObject safety = new JSONObject();
        safety.put( "clientcode", map.get( "clientcode" ) );
        safety.put( "servicecode", map.get( "servicecode" ) );
        safety.put( "time", map.get( "time" ) );
        safety.put( "ticket", map.get( "ticket" ) );
        JSONObject serverbody = new JSONObject();
        serverbody.put( "servername", map.get( "servername" ) );
        serverbody.put( "servertype", map.get( "servertype" ) );
        JSONObject services = new JSONObject();
        JSONObject service = new JSONObject();
        service.put( "serviceid", map.get( "serviceid" ) );
        service.put( "barcode", map.get( "barcode" ) );
        service.put( "filename", map.get( "filename" ) );
        service.put( "content", map.get( "content" ) );
        service.put( "compoanycode", map.get( "compoanycode" ) );
        service.put( "useraccount", map.get( "useraccount" ) );
        service.put( "page", map.get( "page" ) );
        service.put( "totalpage", map.get( "totalpage" ) );
        service.put( "ifhx", map.get( "ifhx" ) );
        services.put( "service", service );
        serverbody.put( "services", services );
        params.put( "safety", safety );
        params.put( "serverbody", serverbody );
        xml.put( "params", params );
        try {
            result = Json2XmlUtils.jsonToPrettyXml( xml );
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    //获取附件内容
    public static byte[] getContent(int fileId){
        byte[] content = new byte[102400];
        // 上传附件，创建html文档
        content = null;
        try {
            int byteread;
            byte data[] = new byte[1024];
            InputStream input = OcrUitl.getInputStreamById( fileId );
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((byteread = input.read(data)) != -1) {
                out.write(data, 0, byteread);
                out.flush();
            }
            content = out.toByteArray();
            input.close();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }
    //获取文件名
    public static String getImagefilename(int fileId){
        RecordSet rs = new RecordSet();
        String sql = "select imagefilename from imagefile where imagefileid in (select imagefileid from docimagefile where docid=" + fileId + ")";
        rs.executeQuery( sql );
        rs.next();
        String imagefilename = Util.null2String( rs.getString( "imagefilename" ) );
        return imagefilename;
    }
    /**
     * 删除单个文件
     *
     * @param fileName 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return Boolean.TRUE;
            } else {
                return Boolean.FALSE;
            }
        } else {
            return Boolean.FALSE;
        }
    }

}
